package com.zjuh.goodboy.index.vector;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.zjuh.goodboy.index.DataProvider;
import com.zjuh.goodboy.items.Item;
import com.zjuh.goodboy.items.ItemUtil;
import com.zjuh.goodboy.store.item.JdbcItemStore;
import com.zjuh.sweet.sql.util.SqlUtil;

public class SqlDataProvider implements DataProvider {

	private DataSource dataSource;
	
	private Connection connection;
	
	private PreparedStatement pstmt;
	
	private ResultSet rs;
	
	public SqlDataProvider(DataSource dataSource) {
		super();
		this.dataSource = dataSource;
	}

	@Override
	public void destroy() {
		SqlUtil.close(rs);
		SqlUtil.close(pstmt);
		SqlUtil.close(connection);
	}

	@Override
	public boolean hasNext() {
		try {
			return rs.next();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void init() {
		try {
			String sql = "select id, " + JdbcItemStore.ITEM_FULL_FIELDS + " from goodboy_item_data";
			connection = dataSource.getConnection();
			pstmt = connection.prepareStatement(sql);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Item next() {
		try {
			return ItemUtil.rsToItem(rs);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
